package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import model.ProductModel;

import dao.Products;

public class CreateProducts extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		double price = Double.parseDouble(request.getParameter("price"));
		int quantities=Integer.parseInt(request.getParameter("quantities"));
		String type_id=request.getParameter("type_id");
		String event_id=request.getParameter("event_id");
		String image_url=request.getParameter("image_url");
		String date_expire=request.getParameter("date_expire");
		ProductModel pObj = new ProductModel(id, name, price,quantities,type_id,event_id,image_url,date_expire);
		Products p = new Products();
		try {
			boolean isExist = p.CheckExistProduct(pObj.getId());
			boolean cp;
			String err = "";
			if(isExist){
				cp = p.UpdateProduct(pObj);
				if (cp) {
					err = "Cập nhật mặt hàng thành công!";
				} else {
					if (p.CheckExistProduct(id)) {
						err = "Mã mặt hàng đã tồn tại!";
					} 
				}
			}else{
				cp = p.CreateProducts(pObj);
				if (cp) {
					err = "Tạo mặt hàng thành công!";
				} else {
					if (p.CheckExistProduct(id)) {
						err = "Mã mặt hàng đã tồn tại!";
					} 
				}
			}
			out.println(err);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
